import { createStore } from 'vuex'
import { getUserInfo } from '../api/user'

export default createStore({
  state: {
    user: JSON.parse(localStorage.getItem('user')) || null,
    token: localStorage.getItem('token')
  },
  mutations: {
    setUser(state, user) {
      state.user = user
      localStorage.setItem('user', JSON.stringify(user))
    },
    setToken(state, token) {
      state.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    logout(state) {
      state.user = null
      state.token = null
      localStorage.removeItem('token')
      localStorage.removeItem('user')
      localStorage.removeItem('rememberMe')
    }
  },
  actions: {
    async checkAuth({ commit, state }) {
      if (!state.token) return
      try {
        const user = await getUserInfo(state.token)
        commit('setUser', user)
      } catch (error) {
        commit('logout')
      }
    }
  },
  getters: {
    isAuthenticated(state) {
      return !!state.token
    },
    userInfo(state) {
      return state.user
    }
  }
}) 